<template>
  <div class="map-wrapper">
    <div id="container" :style="{ height: `${mapHeight}px` }"></div>
  </div>
</template>
<script lang="ts" setup>
import _ from 'lodash'
import { message } from 'ant-design-vue'
import AMapLoader from '@amap/amap-jsapi-loader'
import { useUserStore } from '@/store/modules/user-store'
import { visitApi } from '@/api/business/marketing/visit-api'
import location_fullfilled from '@/assets/images/logo/location_fullfilled.png'
import location_pending from '@/assets/images/logo/location_pending.png'
import location_active from '@/assets/images/logo/location_active.png'

let map: any = null
let AMap: any = null
const icons = {
  location_pending,
  location_active,
  location_fullfilled
}
const userStore = useUserStore()
const route = useRoute()

// 地图高度
const mapHeight = ref(0)

// 初始化地图
function initMap() {
  window._AMapSecurityConfig = {
    securityJsCode: '98ed597fdab99b3580ded9e3d1f19d4e'
  }
  const loadMapConfig = {
    key: 'e3ad28f39ebf5c7d5fb1d7153fb2f3b4', // 申请好的Web端开发者Key，首次调用 load 时必填
    version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: ['AMap.LabelsLayer', 'AMap.Polyline'] //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
  }
  const mapConfig: any = {
    zoom: 14,
    center: userStore.getCenterLocal.map(Number),
    resizeEnable: true
  }

  AMapLoader.load(loadMapConfig).then(async (res) => {
    AMap = res
    // 渲染地图
    mapHeight.value = document.querySelector('.map-wrapper')?.clientHeight || 0
    map = new AMap.Map('container', mapConfig)
    // 请求订单列表
    await getStoreOrderList()
    map.setFitView()
  })
}

// 添加网点坐标
const storesMarkers = ref([])
const storesMarkersList = ref([])
function addMarker() {
  // 创建LabelsLayer图层
  const labelsLayer = new AMap.LabelsLayer({
    zooms: [2, 20], // 设置可见级别范围
    zIndex: 1000, // 设置zIndex
    collision: true, // 设置标签是否允许碰撞
    allowCollision: true // 设置标签是否允许碰撞
  })

  storesMarkers.value = lineNotVisitStoreList.value
    .filter((item) => item.lon && item.lat)
    .map((item, index) => {
      return new AMap.LabelMarker({
        position: new AMap.LngLat(item.lon, item.lat),
        name: item.store_name,
        extData: item,
        icon: {
          type: 'image',
          image: icons['location_active'],
          size: [24, 24],
          anchor: 'bottom-center'
        },
        text: {
          content: `${index + 1}`,
          offset: [0, 20],
          style: {
            fontSize: 10,
            fontWeight: 'normal',
            fillColor: '#000'
          }
        }
      })
    })
  //添加监听事件
  storesMarkers.value.forEach((item) => {
    let infoWindow = null
    item.on('mouseover', (e) => {
      infoWindow = initWindow(e)
      infoWindow.open(map, item.getPosition())
    })
    item.on('mouseout', () => {
      infoWindow.close()
    })
  })

  storesMarkersList.value = lineVisitStoreList.value
    .filter((item) => item.lon && item.lat)
    .map((item, index) => {
      return new AMap.LabelMarker({
        position: new AMap.LngLat(item.lon, item.lat),
        name: item.store_name,
        extData: item,
        icon: {
          type: 'image',
          image: icons['location_pending'],
          size: [24, 24],
          anchor: 'bottom-center'
        },
        text: {
          content: `${index + 1}`,
          offset: [0, 20],
          style: {
            fontSize: 10,
            fontWeight: 'normal',
            fillColor: '#000'
          }
        }
      })
    })
  //添加监听事件
  storesMarkers.value.forEach((item) => {
    let infoWindow = null
    item.on('mouseover', (e) => {
      infoWindow = initWindow(e)
      infoWindow.open(map, item.getPosition())
    })
    item.on('mouseout', () => {
      infoWindow.close()
    })
  })

  //添加监听事件
  storesMarkersList.value.forEach((item) => {
    let infoWindow = null
    item.on('mouseover', (e) => {
      infoWindow = initWindow(e)
      infoWindow.open(map, item.getPosition())
    })
    item.on('mouseout', () => {
      infoWindow.close()
    })
  })

  // 添加仓库标记到图层
  labelsLayer.add(storesMarkers.value)
  labelsLayer.add(storesMarkersList.value)
  map.add(labelsLayer)
}

// 绘制路径
let polyline = undefined
function addPolyline() {
  if (polyline) map.remove(polyline)
  const path = [...lineVisitStoreList.value.map(({ lon, lat }) => [Number(lon), Number(lat)])]
  polyline = new AMap.Polyline({
    path: path, // 设置线覆盖物路径
    showDir: true,
    // dirImg:canvasDir,
    strokeColor: '#3366cc', // 线颜色
    strokeWeight: 10 // 线宽
  })
  map.add(polyline)
}

// 信息窗体
function initWindow(e) {
  const extData = e.target.getExtData()

  const content = `
    <div style="display:flex;flex-direction:column;gap:2px;border: 1px solid #ccc; padding: 10px;background-color: #fff;font-size: 12px">
      <span style="font-weight: bold">${extData.store_name}</span>
      <span>联系人:${extData.contacts}</span>
      <span>门店地址:${extData.address}</span>
      <span>所属路线:${extData.name || 0}</span>
      <span>拜访开始时间:${extData?.sign_in_time || ''}</span>
      <span>拜访结束时间:${extData?.sign_out_time || ''}</span>
      <span>拜访时长:${extData?.visit_duration || 0}</span>
  `
  const infoWindow = new AMap.InfoWindow({
    content: content,
    anchor: 'bottom-center',
    isCustom: true,
    closeWhenClickMap: true,
    offset: [10, -30]
  })
  return infoWindow
}

onMounted(initMap)
onActivated(getStoreOrderList)
onUnmounted(() => {
  map.value?.destroy()
})

// 数据
const lineNotVisitStoreList = ref([])
const lineVisitStoreList = ref([])
async function getStoreOrderList() {
  try {
    const params = {
      id: route.query.id
    }
    console.log(route)
    const res = await visitApi.statisticsDetail(params)
    lineNotVisitStoreList.value = res.data?.lineNotVisitStoreList
    lineVisitStoreList.value = res.data?.lineVisitStoreList
    map?.clearMap()
    addMarker()
    addPolyline()
  } catch (error) {
    if (error?.msg) {
      message.error(error.msg)
    }
  }
}
</script>
<style lang="less" scoped>
.map-wrapper {
  position: relative;
  width: 100%;
  height: 100%;
  #container {
    width: 100%;
    height: auto;
  }
  .order-box {
    position: absolute;
    right: 0;
    top: 0;
    width: 450px;
    .store-order-item {
      position: relative;
      width: 90%;
      font-size: 12px;
      padding: 10px;
      margin-bottom: 5px;
      border-radius: 5px;
      background-color: #f8f9ff;
      cursor: pointer;
      border: 1px solid transparent;
      .no {
        position: absolute;
        left: 15px;
        top: 50%;
        transform: translateY(-50%);
        font-size: 14px;
      }
      .content {
        display: flex;
        flex-direction: column;
        padding-left: 30px;
        width: 100%;
        p {
          width: 100%;
          margin: 0;
          // white-space: nowrap;
          // overflow: hidden;
          // text-overflow: ellipsis;
        }
        .line {
          color: #8085a2;
        }
        .line span {
          color: #000;
        }
      }
      .order-info-line {
        display: flex;
        gap: 5px;
        align-items: center;
      }
    }
    .store-order-item.active,
    .store-order-item:hover {
      background-color: #eaf4f0;
      border: 1px solid @primary-color;
    }
  }
  .order-box-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 12px;
  }
  .total-box {
    position: absolute;
    left: -100%;
    bottom: 0px;
    transform: translateX(60%);
    font-size: 12px;
    .total-box-line {
      display: flex;
      justify-content: space-between;
      margin-bottom: 0;
      strong {
        font-size: 14px;
      }
      span {
        width: fit-content;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }
}
</style>
